﻿using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Cl.Utils.Helper
{
    public static class UtilHelper
    {

        public static bool CheckJson(string jsonStr)
        {
            try
            {
                // 使用 Newtonsoft.Json
                JObject.Parse(jsonStr);
                // 或者使用 System.Text.Json
                // JsonDocument.Parse(str).RootElement;

                return true;
            }
            catch (JsonReaderException)
            {
                return false;
            }
        }

        public static bool CheckJson(JsonDocument? obj)
        {
            try
            {
                if (obj == null)
                    return false;
                var jsonStr = obj.RootElement.ToString();

                JObject.Parse(jsonStr);
                //JsonDocument.Parse(jsonStr);

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public static bool CheckJson(object? obj)
        {
            try
            {
                string json = JsonConvert.SerializeObject(obj);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        public static string GetClientIpAddress(HttpRequest request)
        {
            if (request.Headers.ContainsKey("X-Forwarded-For"))
            {
                // 如果请求经过了代理服务器，X-Forwarded-For可能包含多个IP地址，第一个通常是客户端的IP
                var header = request.Headers["X-Forwarded-For"];
                if (!string.IsNullOrEmpty(header))
                    return header.ToString().Split(",").FirstOrDefault();
                else return "";
            }
            else
            {
                return request.HttpContext.Connection.RemoteIpAddress.ToString();
            }
        }

        public static string GetUrlQueryParams(string strUrl)
        {
            try
            {

                Uri uri = new Uri(strUrl);

                // 获取查询字符串
                string query = uri.Query;

                // 移除查询字符串前的问号
                if (query.StartsWith("?"))
                {
                    query = query.Substring(1);
                }

                return query;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public static string GetUserAgent(HttpContext httpContext)
        {
            var result = string.Empty;

            string userAgent = httpContext.Request.Headers["User-Agent"].ToString();

            if (userAgent.Contains("Postman"))
            {
                // 请求来自Postman
                result = "Postman";
            }
            else if (userAgent.Contains("Edg") || userAgent.Contains("Edge"))
            {
                // 请求来自Microsoft Edge浏览器
                result = "Microsoft Edge";
            }
            else if (userAgent.Contains("Chrome"))
            {
                // 请求来自浏览器
                //Console.WriteLine("请求来自Google Chrome浏览器");
                result = "Google Chrome";
            }
            else
            {
                // 其他类型或未识别的浏览器/客户端
                //Console.WriteLine("请求来自未知或未指定的浏览器/客户端");
            }


            return result;
        }

        public static JObject ConvertToJObject(string jsonStr)
        {
            try
            {
                // 使用 Newtonsoft.Json
                var data = JObject.Parse(jsonStr);
                return data;
            }
            catch (JsonReaderException)
            {
                return new JObject();
            }
        }

        /// <summary>
        /// 显示对象的所有属性及其值。
        /// </summary>
        /// <param name="obj">要显示属性的对象。</param>
        public static Dictionary<string, string> DisplayProperties(object obj)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            // 获取对象的类型
            var type = obj.GetType();

            // 获取对象的所有属性
            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            // 遍历所有属性并输出属性名称和值
            foreach (var property in properties)
            {
                //Console.WriteLine($"{property.Name}: {property.GetValue(obj)}");
                result.Add(property.Name, property.GetValue(obj).ToString());
            }
            return result;
        }

        /// <summary>
        /// 显示类中的所有 const 常量及其值。
        /// </summary>
        /// <param name="type">包含 const 常量的类型。</param>
        public static Dictionary<string, string> DisplayConstValues(Type type)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            // 获取类的所有字段
            var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

            // 遍历所有字段并输出 const 常量的名称和值
            foreach (var field in fields)
            {
                if (field.IsLiteral)
                {
                    //Console.WriteLine($"{field.Name}: {field.GetValue(null)}");
                    result.Add(field.Name, field.GetValue(null).ToString());
                }
            }
            return result;
        }

        /// <summary>
        /// 获取指定日期的当前月
        /// </summary>
        /// <returns></returns>
        public static DateTime GetMonthDateTime(DateTime dt)
        {
            return new DateTime(dt.Year, dt.Month, 1);//获取本月的起始日期


        }

        public static DateTime GetWeekDateTime(DateTime dt, DayOfWeek startOfWeek)
        {
            int dayOfWeek = (int)dt.DayOfWeek;
            int diff = dayOfWeek - (int)startOfWeek;
            if (diff < 0) diff += 7;
            return dt.AddDays(-1 * diff).Date;
        }
    }
}
